import 'package:eyepetizer_example/config/string.dart';
import 'package:eyepetizer_example/page/hot/hot_list_page.dart';
import 'package:eyepetizer_example/widget/app_bar.dart';
import 'package:eyepetizer_example/widget/tab_bar.dart';
import 'package:flutter/material.dart';

import '../http/Url.dart';
import '../http/http_manager.dart';
import '../model/hot/tab_info_model.dart';
import '../utils/toast_util.dart';

class HotPage extends StatefulWidget {
  const HotPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _HotPageState();
}

class _HotPageState extends State<StatefulWidget>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  late TabController _tabController;
  List<TabInfoItem> _tabList = [];
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabList.length, vsync: this);
    _pageController = PageController();
    loadData();
  }

  @override
  void setState(VoidCallback fn) {
    //判断是否渲染完成，防止数据还没有获取到，此时setState触发的控件渲染就会报错
    if (mounted) {
      super.setState(fn);
    }
  }

  @override
  void dispose() {
    _tabController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: appBar(AppString.popularity_list, showBack: false),
      body: Column(
        children: [
          tabBar(
              controller: _tabController,
              // tab 标签
              tabs: _tabList
                  .map((tabInfoItem) => Tab(
                        text: tabInfoItem.name ?? "",
                      ))
                  .toList(),
              // 点击 TabBar 切换 page
              onTap: (index) => _pageController.animateToPage(index,
                  // 切换page的时间：300ms
                  duration: kTabScrollDuration,
                  // 快速加速并缓慢结束的动画
                  curve: Curves.ease)),
          Expanded(child: PageView(
            controller: _pageController,
            onPageChanged: (index)=> _tabController.index = index,
            children: _tabList.map((tabInfoItem) => HotListPage(apiUrl: tabInfoItem.apiUrl??"")).toList(),
          ))
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  void loadData() {
    HttpManager.getData(
      Url.rankUrl,
      success: (result) {
        TabInfoModel tabInfoModel = TabInfoModel.fromJson(result);
        setState(() {
          _tabList = tabInfoModel.tabInfo?.tabList??[];
          _tabController = TabController(length: _tabList.length, vsync: this);
        });
      },
      fail: (e) {
        AppToast.showError(e.toString());
      },
    );
  }
}
